<template>
  <view class="container">
    <!-- 相机组件 -->
    <camera class="camera" device-position="back" flash="off" @error="cameraError"></camera>

    <!-- 水印覆盖层（实时预览） -->
    <cover-view class="watermark">
      <cover-image v-if="watermarkImage" :src="watermarkImage" class="watermark-img" />
      <cover-view v-else class="watermark-text">{{ watermarkText }}</cover-view>
    </cover-view>

    <!-- 操作按钮 -->
    <cover-view class="controls">
      <button @click="takePhoto">拍摄</button>
      <button @click="switchCamera">切换摄像头</button>
    </cover-view>

    <!-- 隐藏的Canvas（用于图片处理） -->
    <canvas canvas-id="photoCanvas" class="canvas"
      :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"></canvas>
  </view>
</template>

<script setup>
  import {
    ref,
    onMounted
  } from 'vue';
  import {
    uploadFilePromise
  } from '@/utils/upload';
  const cameraContext = ref(null);
  const canvasWidth = ref(300);
  const canvasHeight = ref(400);
  const watermarkText = ref('机密文件');
  const watermarkImage = ref('../../static/logo.jpg');

  // 初始化相机
  onMounted(() => {
    cameraContext.value = uni.createCameraContext();
  });

  // 拍照功能
  const takePhoto = () => {
    cameraContext.value.takePhoto({
      quality: 'high',
      success: (res) => {
        addWatermarkToPhoto(res.tempImagePath);
      },
      fail: (err) => {
        uni.showToast({
          title: '拍照失败',
          icon: 'none'
        });
      }
    });
  };

  // 添加水印到照片
  const addWatermarkToPhoto = async (tempFilePath) => {
    const ctx = uni.createCanvasContext('photoCanvas', this);

    // 获取图片信息
    const imgInfo = await getImageInfo(tempFilePath);

    // 设置Canvas尺寸与图片一致
    canvasWidth.value = imgInfo.width;
    canvasHeight.value = imgInfo.height;

    // 绘制原始图片
    ctx.drawImage(tempFilePath, 0, 0, imgInfo.width, imgInfo.height);

    // 添加文字水印
    ctx.setFontSize(30);
    ctx.setFillStyle('rgba(255, 0, 0, 0.5)');
    ctx.fillText(watermarkText.value, 20, imgInfo.height - 50);

    // 添加图片水印（可选）
    if (watermarkImage.value) {
      const watermarkInfo = await getImageInfo(watermarkImage.value);
      ctx.drawImage(
        watermarkImage.value,
        imgInfo.width - watermarkInfo.width - 20,
        imgInfo.height - watermarkInfo.height - 20,
        watermarkInfo.width,
        watermarkInfo.height
      );
    }

    // 生成最终图片
    ctx.draw(false, () => {
      uni.canvasToTempFilePath({
        canvasId: 'photoCanvas',
        success: (res) => {
          uploadFilePromise(res.tempFilePath).then((result) => {
            uni.showToast({
              title: '上传成功',
              icon: 'none'
            })
            console.log(result)
            savePhoto(res.tempFilePath);
          })


        },
        fail: (err) => {
          console.error('Canvas生成失败:', err);
        }
      });
    });
  };

  // 保存图片到相册
  const savePhoto = (tempFilePath) => {
    uni.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success: () => {
        uni.showToast({
          title: '保存成功'
        });
      },
      fail: (err) => {
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    });
  };

  // 获取图片信息
  const getImageInfo = (path) => {
    return new Promise((resolve, reject) => {
      uni.getImageInfo({
        src: path,
        success: resolve,
        fail: reject
      });
    });
  };

  // 切换摄像头
  const switchCamera = () => {
    // 需要重新创建CameraContext
    cameraContext.value = uni.createCameraContext();
  };
</script>

<style>
  .container {
    position: relative;
    width: 100vw;
    height: 100vh;
  }

  .camera {
    width: 100%;
    height: 100%;
  }

  .watermark {
    position: absolute;
    bottom: 100px;
    right: 20px;
    color: rgba(255, 0, 0, 0.3);
    font-size: 20px;
    pointer-events: none;
  }

  .watermark-img {
    width: 100px;
    height: 100px;
    opacity: 0.5;
  }

  .controls {
    position: fixed;
    bottom: 20px;
    width: 100%;
    display: flex;
    justify-content: space-around;
  }

  .canvas {
    position: fixed;
    top: -9999px;
    left: -9999px;
  }
</style>
